package com.nl.controller.sms5g.controller;


import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.global.GlobalConstants;
import com.nl.controller.common.util.BaseResult;
import com.nl.controller.sms5g.bean.bo.CreateUploadRecordBo;
import com.nl.controller.sms5g.mapper.Sms5gSignatureMapper;
import com.nl.controller.sms5g.mapper.Sms5gTemplateMapper;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @desc 
 * @return null
 * @author l
 * @date 2021/6/8 9:28
 */
@Slf4j
@Controller
@RequestMapping(value = "/upload")
public class Sms5gFileUploadController {

    @Autowired
    private Sms5gTemplateMapper sms5gTemplateMapper;

    /**
     * layeditor编辑器内使用上传文件
     * @param request
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/layeditorfile")
    public String layeditorfile(HttpServletRequest request, @Param("file") MultipartFile file) {
        Map<String, Object> map = new HashMap<String, Object>();
        //PageData pd = new PageData();
        //原始名称
        String originalFilename = file.getOriginalFilename();
        //pd.put("title", originalFilename);//图片名称，这个会显示在输入框里
        Map<String, String> pd = new HashMap<>();
        // 上传文件
        //List<Map<String, String>> files = FileUtil.fileUpload(file,request, GlobalConst.SIGNNATURE_FILE_PATH,originalFilename);
        String uploadResult = FileUtil.fileUpload(file,request, GlobalConst.MULTI_FILE_PATH,originalFilename);
        if ("fail".equals(uploadResult)) {
            //图片url
            pd.put("src", "");
            //0表示成功，-1失败
            map.put("code", -1);
            //提示消息
            map.put("msg", "上传失败");
            map.put("data", pd);
        } else {
            String filePath = GlobalConst.MULTI_FILE_PATH+originalFilename;

            //图片url
            pd.put("src", filePath);
            //0表示成功，1失败
            map.put("code", 0);
            //提示消息
            map.put("msg", "上传成功");
            map.put("data", pd);
        }

        String result = new JSONObject(map).toString();
        return result;
    }

    /**
     * 文件上传：兼容多图和单图，目前代码实现中layui.upload多图上传会多次调用该接口，相当于多次上传单图
     *
     * @param multipartRequest
     * @return
     * @throws Exception
     */
//    @RequestMapping(value = "/file", produces = "application/json;charset=UTF-8")
//    @ResponseBody
//    public Object fileupload(DefaultMultipartHttpServletRequest multipartRequest) throws Exception {
//        return fileUploadWithPath("default/", multipartRequest);
//    }

    /**
     * 文件上传：兼容多图和单图，目前代码实现中layui.upload多图上传会多次调用该接口，相当于多次上传单图
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/templateFile", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public BaseResult fileUpload(@Param("file")MultipartFile file,HttpServletRequest request,String mgrId,String type) throws Exception {

        System.out.println("------"+type);
        BaseResult baseResult = BaseResult.newFailInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(new Date());
        Map<String, Object> map = new HashMap<String, Object>();
        String uploadResult = "";
        int uploadCount = 0;
        String filePath = "";
        String fileThumb = "";
        String fileType = "";
        String typeName = "";
        String finalFileName = "";

        try {
                //首先判断是不是空的文件
                if (!file.isEmpty()) {
                    //原始名称
                    String originalFilename = file.getOriginalFilename();
                    //对文文件的全名进行截取然后在后缀名进行删选。
                    int begin = file.getOriginalFilename().indexOf(".");
                    int last = file.getOriginalFilename().length();
                    //获得文件后缀名
                    typeName = file.getOriginalFilename().substring(begin, last);
                    finalFileName = mgrId+"_"+sdf2.format(new Date())+typeName;
                    //存服务器
                    uploadResult = FileUtil.fileUpload(file,request, GlobalConst.MULTI_FILE_PATH+"/",finalFileName);
                    if("success".equals(uploadResult)){
                        uploadCount++;
                        CreateUploadRecordBo createUploadRecordBo = new CreateUploadRecordBo();
                        createUploadRecordBo.setMgrId(mgrId);
                        createUploadRecordBo.setType(type);
                        createUploadRecordBo.setFileName(finalFileName);
                        //新增上传记录
                        sms5gTemplateMapper.createUploadRecord(createUploadRecordBo);
                        if ("".equals(filePath)) {
                            filePath = finalFileName;
                        } else {
                            filePath = filePath + "," +finalFileName;
                        }
                    }

                    // 上传文件
                    if (uploadCount < 1) {
                        baseResult.setRetCode(GlobalConstants.FAIL_STRING);
                        baseResult.setRetMsg("上传失败，文件为空");
                    }else{
                        baseResult.setRetCode(GlobalConstants.SUCCESS_STRING);
                        baseResult.setRetMsg("文件上传成功");
                        baseResult.setData(filePath);

                    }
                }else{
                    baseResult.setRetCode(GlobalConstants.FAIL_STRING);
                    baseResult.setRetMsg("上传失败，文件为空");
                }
        } catch (Exception e) {
            e.printStackTrace();
            baseResult.setRetCode(GlobalConstants.EXCEPTION_STRING);
            baseResult.setRetMsg("文件上传发生异常");
        }
        return baseResult;
    }

    /**
     * 根据文件路径删除文件
     *
     * @param filePath
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/delete")
    public BaseResult deleteFile(@RequestParam(value = "mgrId", required = true)String mgrId, @RequestParam(value = "filePath", required = true)String filePath) throws Exception {
        BaseResult baseResult = BaseResult.newFailInstance();
        double bytes = 0;
        double kilobytes =0;
        log.info("====="+mgrId+"======"+filePath);
        try {
            //文件名不为空且不是文本内容
            if (null != filePath && !filePath.contains(".txt")) {
                File file = new File(GlobalConst.MULTI_FILE_PATH+filePath);
                if(file.exists()){
                    bytes = file.length();
                    kilobytes = (bytes / 1024);
                    file.delete();
                }
            }
            int deleteResult = sms5gTemplateMapper.deleteUploadRecord(mgrId,filePath);
            baseResult.setRetCode(GlobalConstants.SUCCESS_STRING);
            baseResult.setRetMsg("文件删除成功");
            baseResult.setData(kilobytes);
        } catch (Exception e) {
            e.printStackTrace();
            baseResult.setRetCode(GlobalConstants.EXCEPTION_STRING);
            baseResult.setRetMsg("文件删除出现异常");
        }
        return baseResult;
    }

    /**
     * @desc 模板文字上传
     * @param mgrId
     * @param content
     * @return java.lang.Object
     * @author l
     * @date 2021/6/10 15:37
     */
    @ResponseBody
    @RequestMapping("/uploadContent")
    public BaseResult uploadContent(@RequestParam(value = "mgrId", required = true)String mgrId,String content){
        BaseResult baseResult = BaseResult.newFailInstance();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH24mmss");
            String name = mgrId+"_"+sdf.format(new Date())+".txt";
            CreateUploadRecordBo createUploadRecordBo = new CreateUploadRecordBo();
            createUploadRecordBo.setMgrId(mgrId);
            createUploadRecordBo.setType("text");
            createUploadRecordBo.setFileName(name);
            int insertResult = sms5gTemplateMapper.createUploadRecord(createUploadRecordBo);
            baseResult.setData(name);
            baseResult.setRetCode(GlobalConstants.SUCCESS_STRING);
            baseResult.setRetMsg("模板文本上传成功");
        }catch (Exception e){
            e.printStackTrace();
            baseResult.setRetCode(GlobalConstants.EXCEPTION_STRING);
            baseResult.setRetMsg("模板文本上传出现异常");
        }
        return baseResult;
    }
}